/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spidercore;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

/**
 *
 * @author Lone_Wolf
 */
public class Torrific {

    private String domain = "http://www.torrific.com";
    private String crsfTokenValue;
    private CookieManager cm;
    private ConnectionTools ct;
    private ArrayList<TorrificTorrent> liste = new ArrayList<TorrificTorrent>();

    public Torrific() {
        crsfTokenValue = "";
        cm = new CookieManager();
        ct = new ConnectionTools();

        getLoginWithCookieManager();
        getHomeWithCookieManager();
        
        getTorrentPage("/torrage.com/torrent/EAB859542ECC1E0B0BEF75A42B569FB1E7A23695"
                + ".torrent?title=[kat.ph]david.guetta.nothing.but.the.beat."
                + "international.edition.itun");
    }

    public void store_crsfToken(URLConnection conn) {
        crsfTokenValue = conn.getHeaderField("Set-Cookie");
        crsfTokenValue = crsfTokenValue.substring(crsfTokenValue.indexOf("crsftoken=") + 11);
        crsfTokenValue = crsfTokenValue.substring(0, crsfTokenValue.indexOf(";"));
        //System.out.println(crsfTokenValue);
    }

    public void getLoginWithCookieManager() {
        try {
            // connect to URL
            URL url = new URL("http://www.torrific.com/login/");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setDoOutput(true);
            conn.connect();

            // print headers
            ct.printHeaders(conn, false);

            // store cookies
            cm.storeCookies(conn);

            // store crsfToken
            store_crsfToken(conn);

            // get response
            ct.getContent(conn, false, false);

            //we are ready to send the login request
            //open connection
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            cm.setCookies(conn);
            conn.connect();

            //send request
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            String message = "csrfmiddlewaretoken=" + crsfTokenValue + "&email=lonewolf236%40gmail.com&password=smarties&next=%2F";
            dos.writeBytes(message);
            dos.flush();
            dos.close();
            //System.out.println("\n----------------------------------------------\n");

            //get and store cookies of the answer
            cm.storeCookies(conn);

            // get headers of the answer
            ct.printHeaders(conn, false);

            // get content of the answer
            ct.getContent(conn, false, false);

            // print cookies
            //System.out.println(cm);
            //we have the sessionid!
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

    public void getHomeWithCookieManager() {
        try {
            boolean gzip = true;

            // connect to URL
            URL url = new URL("http://www.torrific.com/home/");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setDoOutput(true);
            if (gzip) {
                conn.addRequestProperty("Accept-Encoding", "gzip");
            }
            cm.setCookies(conn);
            conn.connect();

            // get headers
            ct.printHeaders(conn, false);

            //get, store and set cookies
            cm.storeCookies(conn);

            // get response and parse it
            parse_Home(ct.getContent(conn, false, gzip));

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    
    public void getTorrentPage(String lien){
        try {
            boolean gzip = true;

            // connect to URL
            URL url = new URL(domain + lien);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            conn.setDoOutput(true);
            if (gzip) {
                conn.addRequestProperty("Accept-Encoding", "gzip");
            }
            cm.setCookies(conn);
            conn.connect();

            // get headers
            ct.printHeaders(conn, true);

            //get, store and set cookies
            cm.storeCookies(conn);

            // get response and parse it
            parse_TorrentFiles(ct.getContent(conn, true, gzip));

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public void parse_Home(String input) {
        int index = 0;
        int indexfin = 0;
        String temp = "";

        //parse the different torrents
        while (index != -1) {
            index++;
            index = input.indexOf("<tr", index);
            if (index != -1) {
                indexfin = input.indexOf("</tr", index);
                temp = input.substring(index, indexfin);
                if (temp.contains("overflow:hidden")) {
                    liste.add(new TorrificTorrent(input.substring(index, indexfin)));
                }
            }
        }
        //System.out.println(liste.size() + " Torrents in total");
    }
    
    public void parse_TorrentFiles(String input){
        int index = 0;
        int indexfin = 0;
        String temp = "";
        int compteur = 0;

        //parse the different torrents
        while (index != -1) {
            index++;
            index = input.indexOf("href", index);
            if (index != -1) {
                indexfin = input.indexOf("\">", index);
                //temp = input.substring(index, indexfin);
                compteur++;
            }
        }
        System.out.println(compteur + " Files in this torrent");
    }
}
